package top.pcat.codecs;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import top.pcat.entity.Message;
import top.pcat.util.ProtostuffUtils;

import java.util.List;


public class MessageCodec extends ByteToMessageCodec<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {

        byte[] bytes = ProtostuffUtils.serialize(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
        //ReferenceCountUtil.release(out);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int length = in.readInt();

        byte[] bytes = new byte[length];
        in.readBytes(bytes, 0, length);
        Message deserialize = ProtostuffUtils.deserialize(bytes, Message.class);
        out.add(deserialize);
        //ReferenceCountUtil.release(in);
    }
}